package bookmanagementsystem.gui;

import bookmanagementsystem.dao.AdminDAO;
import bookmanagementsystem.model.Admin;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AdminLoginFrame extends JFrame {

    public AdminLoginFrame() {
        setTitle("图书管理系统 - 管理员登录");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        initUI();
    }

    private void initUI() {
        JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));

        JTextField adminIDField = new JTextField(20);
        JPasswordField passwordField = new JPasswordField(20);

        JButton loginButton = new JButton("登录");
        JButton registerButton = new JButton("注册");

        panel.add(new JLabel("管理员ID："));
        panel.add(adminIDField);
        panel.add(new JLabel("密码："));
        panel.add(passwordField);
        panel.add(loginButton);
        panel.add(registerButton);

        getContentPane().add(panel);

        // 登录按钮点击事件处理
        loginButton.addActionListener(new LoginButtonListener(adminIDField, passwordField));

        // 注册按钮点击事件处理
        registerButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                AdminRegistrationFrame adminRegistrationFrame = new AdminRegistrationFrame();
                adminRegistrationFrame.setVisible(true);
            }
        });

        setVisible(true);
    }

    private  class LoginButtonListener implements ActionListener {
        private JTextField adminIDField;
        private JPasswordField passwordField;

        public LoginButtonListener(JTextField adminIDField, JPasswordField passwordField) {
            this.adminIDField = adminIDField;
            this.passwordField = passwordField;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String adminID = adminIDField.getText();
            String password = new String(passwordField.getPassword());

            AdminDAO adminDAO = new AdminDAO();
            if (adminDAO.loginAdmin(adminID, password)) {
                JOptionPane.showMessageDialog(null, "登录成功！");
                AdminMainFrame adminMainFrame = new AdminMainFrame(adminID);
                adminMainFrame.setVisible(true);
                dispose();
            } else {
                JOptionPane.showMessageDialog(null, "登录失败，请检查管理员ID和密码。");
            }
        }
    }

    public static void main(String[] args) {

        LoginFrame loginFrame = new LoginFrame();
    }
}